package com.xyh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyh.dao.TypeMapper;
import com.xyh.exception.NotFoundException;
import com.xyh.pojo.PageRequest;
import com.xyh.pojo.PageResult;
import com.xyh.pojo.PageUtils;
import com.xyh.pojo.Type;
import com.xyh.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeMapper typeMapper;
    @Transactional
    @Override
    public int saveType(Type type) {
        return typeMapper.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeMapper.findOne(id);
    }

    @Transactional
    @Override
    public int updateType(Long id, Type type) {
        Type t = typeMapper.findOne(id);
        if (t == null) {
            throw new NotFoundException("不存在该分类");
        }
        return typeMapper.update(id,type);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeMapper.delete(id);
    }

    /**
     * 调用分页插件完成分页
     * @param pageRequest 自定义，统一分页查询请求
     * @return 分页结果
     */
    @Override
    public PageResult getPage(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Type> typeList = typeMapper.getAll();
        PageInfo<Type> pageInfo = new PageInfo<>(typeList);
        return PageUtils.getPageResult(pageInfo);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeMapper.getTypeByName(name);
    }

    @Override
    public List<Type> getAll() {
        return typeMapper.getAll();
    }

    @Override
    public List<Type> getTypeTop(Integer size) {
        return typeMapper.getTypeTop(size);
    }
}
